<template>
	<div class="diy_edit page_catering_orders" id="catering_orders_edit">
		<div class='warp'>
			<div class='container'>
				<div class='row diy_edit_content_box'>
						<div v-if="$check_field('set','merchant_users') || $check_field('add','merchant_users') || $check_field('get','merchant_users')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								商家用户:
							</span>
						</div>
						<div class="diy_field diy_down">
							<select id="form_merchant_users" :disabled="disabledObj['merchant_users_isDisabled']" v-model="form['merchant_users']" v-if="(form['merchant_users'] && $check_field('set','merchant_users')) || (!form['merchant_users'] && $check_field('add','merchant_users'))" >
								<option v-for="o in list_user_merchant_users" :value="o['user_id']">
									{{o['nickname'] + '-' + o['username']}}
								</option>
							</select>
							<span v-else-if="$check_field('get','merchant_users')">{{ get_user_info("merchant_users", form['merchant_users']) }}</span>
						</div>
					</div>
							<div v-if="$check_field('set','merchant_name') || $check_field('add','merchant_name') || $check_field('get','merchant_name')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								商家姓名:
							</span>
						</div>
								<!-- 文本 -->
									<div class="diy_field diy_text">
							<input type="text" id="form_merchant_name" v-model="form['merchant_name']" placeholder="请输入商家姓名" v-if="(form['merchant_name'] && $check_field('set','merchant_name')) || (!form['merchant_name'] && $check_field('add','merchant_name'))"  :disabled="disabledObj['merchant_name_isDisabled']"/>
							<span v-else-if="$check_field('get','merchant_name')">{{ form['merchant_name'] }}</span>
						</div>
										</div>
							<div v-if="$check_field('set','name_of_homestay') || $check_field('add','name_of_homestay') || $check_field('get','name_of_homestay')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								民宿名称:
							</span>
						</div>
								<!-- 文本 -->
									<div class="diy_field diy_text">
							<input type="text" id="form_name_of_homestay" v-model="form['name_of_homestay']" placeholder="请输入民宿名称" v-if="(form['name_of_homestay'] && $check_field('set','name_of_homestay')) || (!form['name_of_homestay'] && $check_field('add','name_of_homestay'))"  :disabled="disabledObj['name_of_homestay_isDisabled']"/>
							<span v-else-if="$check_field('get','name_of_homestay')">{{ form['name_of_homestay'] }}</span>
						</div>
										</div>
							<div v-if="$check_field('set','food_name') || $check_field('add','food_name') || $check_field('get','food_name')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								美食名称:
							</span>
						</div>
								<!-- 文本 -->
									<div class="diy_field diy_text">
							<input type="text" id="form_food_name" v-model="form['food_name']" placeholder="请输入美食名称" v-if="(form['food_name'] && $check_field('set','food_name')) || (!form['food_name'] && $check_field('add','food_name'))"  :disabled="disabledObj['food_name_isDisabled']"/>
							<span v-else-if="$check_field('get','food_name')">{{ form['food_name'] }}</span>
						</div>
										</div>
							<div v-if="$check_field('set','food_prices') || $check_field('add','food_prices') || $check_field('get','food_prices')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								美食价格:
							</span>
						</div>
								<!-- 数字 -->
						<div class="diy_field diy_number">
							<input type="number" id="form_food_prices" v-model.number="form['food_prices']" placeholder="请输入美食价格" v-if="(form['food_prices'] && $check_field('set','food_prices')) || (!form['food_prices'] && $check_field('add','food_prices'))" :disabled="disabledObj['food_prices_isDisabled']" />
							<span v-else-if="$check_field('get','food_prices')">{{ form['food_prices'] }}</span>
						</div>
							</div>
							<div v-if="$check_field('set','ordinary_users') || $check_field('add','ordinary_users') || $check_field('get','ordinary_users')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								普通用户:
							</span>
						</div>
						<div class="diy_field diy_down">
							<select id="form_ordinary_users" :disabled="disabledObj['ordinary_users_isDisabled']" v-model="form['ordinary_users']" v-if="(form['ordinary_users'] && $check_field('set','ordinary_users')) || (!form['ordinary_users'] && $check_field('add','ordinary_users'))" >
								<option v-for="o in list_user_ordinary_users" :value="o['user_id']">
									{{o['nickname'] + '-' + o['username']}}
								</option>
							</select>
							<span v-else-if="$check_field('get','ordinary_users')">{{ get_user_info("ordinary_users", form['ordinary_users']) }}</span>
						</div>
					</div>
							<div v-if="$check_field('set','user_name') || $check_field('add','user_name') || $check_field('get','user_name')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								用户姓名:
							</span>
						</div>
								<!-- 文本 -->
									<div class="diy_field diy_text">
							<input type="text" id="form_user_name" v-model="form['user_name']" placeholder="请输入用户姓名" v-if="(form['user_name'] && $check_field('set','user_name')) || (!form['user_name'] && $check_field('add','user_name'))"  :disabled="disabledObj['user_name_isDisabled']"/>
							<span v-else-if="$check_field('get','user_name')">{{ form['user_name'] }}</span>
						</div>
										</div>
							<div v-if="$check_field('set','purchase_quantity') || $check_field('add','purchase_quantity') || $check_field('get','purchase_quantity')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								购买数量:
							</span>
						</div>
								<!-- 数字 -->
						<div class="diy_field diy_number">
							<input type="number" id="form_purchase_quantity" v-model.number="form['purchase_quantity']" placeholder="请输入购买数量" v-if="(form['purchase_quantity'] && $check_field('set','purchase_quantity')) || (!form['purchase_quantity'] && $check_field('add','purchase_quantity'))" :disabled="disabledObj['purchase_quantity_isDisabled']" />
							<span v-else-if="$check_field('get','purchase_quantity')">{{ form['purchase_quantity'] }}</span>
						</div>
							</div>
							<div v-if="$check_field('set','total_purchase_price') || $check_field('add','total_purchase_price') || $check_field('get','total_purchase_price')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								购买总价:
							</span>
						</div>
								<!-- 计算 -->
						<div class="diy_field diy_compute">
							<span v-if="$check_field('get','total_purchase_price')">{{ toFixed(form['food_prices'] * form['purchase_quantity']) }}</span>
						</div>
							</div>
							<div v-if="$check_field('set','room_location') || $check_field('add','room_location') || $check_field('get','room_location')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								房间位置:
							</span>
						</div>
								<!-- 文本 -->
									<div class="diy_field diy_text">
							<input type="text" id="form_room_location" v-model="form['room_location']" placeholder="请输入房间位置" v-if="(form['room_location'] && $check_field('set','room_location')) || (!form['room_location'] && $check_field('add','room_location'))"  :disabled="disabledObj['room_location_isDisabled']"/>
							<span v-else-if="$check_field('get','room_location')">{{ form['room_location'] }}</span>
						</div>
										</div>
							<div v-if="$check_field('set','a_room_number') || $check_field('add','a_room_number') || $check_field('get','a_room_number')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								房间号码:
							</span>
						</div>
								<!-- 文本 -->
									<div class="diy_field diy_text">
							<input type="text" id="form_a_room_number" v-model="form['a_room_number']" placeholder="请输入房间号码" v-if="(form['a_room_number'] && $check_field('set','a_room_number')) || (!form['a_room_number'] && $check_field('add','a_room_number'))"  :disabled="disabledObj['a_room_number_isDisabled']"/>
							<span v-else-if="$check_field('get','a_room_number')">{{ form['a_room_number'] }}</span>
						</div>
										</div>
							<div v-if="$check_field('set','memo') || $check_field('add','memo') || $check_field('get','memo')" class="form-item col-12 col-md-6">
						<div class="diy_title">
							<span>
								备注信息:
							</span>
						</div>
								<!-- 多文本 -->
						<div class="diy_field diy_desc">
							<textarea id="form_memo" v-model="form['memo']" v-if="(form['memo'] && $check_field('set','memo')) || (!form['memo'] && $check_field('add','memo'))" :disabled="disabledObj['memo_isDisabled']" />
							<span v-else-if="$check_field('get','memo')">{{ form['memo'] }}</span>
						</div>
							</div>
	




				</div>
				<div class="diy_edit_submit_box row">
					<div class="col-12">
						<div class="btn_box">
							<button class="btn_submit" @click="submit()">提交</button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import mixin from "@/mixins/page.js";
	export default {
		mixins: [mixin],
		components: {},
		data() {
			return {
				url_get_obj: "~/api/catering_orders/get_obj?",
				url_add: "~/api/catering_orders/add?",
				url_set: "~/api/catering_orders/set?",

				// 登录权限
				oauth: {
					"signIn": true,
					"user_group": []
				},

				// 查询条件
				query: {
						"merchant_users": 0,
							"merchant_name": "",
							"name_of_homestay": "",
							"food_name": "",
							"food_prices": 0,
							"ordinary_users": 0,
							"user_name": "",
							"purchase_quantity": 0,
							"total_purchase_price": 0,
							"room_location": "",
							"a_room_number": "",
							"memo": "",
						"catering_orders_id": 0,
				},

				obj: {
						"merchant_users": 0, // 商家用户
							"merchant_name":  '', // 商家姓名
							"name_of_homestay":  '', // 民宿名称
							"food_name":  '', // 美食名称
							"food_prices":  0, // 美食价格
							"ordinary_users": 0, // 普通用户
							"user_name":  '', // 用户姓名
							"purchase_quantity":  0, // 购买数量
							"total_purchase_price": 0, // 购买总价
							"room_location":  '', // 房间位置
							"a_room_number":  '', // 房间号码
							"memo":  '', // 备注信息
						"catering_orders_id": 0,
				},

				// 表单字段
				form: {
						"merchant_users": 0, // 商家用户
							"merchant_name":  '', // 商家姓名
							"name_of_homestay":  '', // 民宿名称
							"food_name":  '', // 美食名称
							"food_prices":  0, // 美食价格
							"ordinary_users": 0, // 普通用户
							"user_name":  '', // 用户姓名
							"purchase_quantity":  0, // 购买数量
							"total_purchase_price": 0, // 购买总价
							"room_location":  '', // 房间位置
							"a_room_number":  '', // 房间号码
							"memo":  '', // 备注信息
						"catering_orders_id": 0,
				},
				disabledObj:{
						"merchant_users_isDisabled": false,
							"merchant_name_isDisabled": false,
							"name_of_homestay_isDisabled": false,
							"food_name_isDisabled": false,
									"ordinary_users_isDisabled": false,
							"user_name_isDisabled": false,
											"room_location_isDisabled": false,
							"a_room_number_isDisabled": false,
							"memo_isDisabled": false,
					},

						// 用户列表
				list_user_merchant_users: [],
																				// 用户列表
				list_user_ordinary_users: [],
																				
				// ID字段
				field: "catering_orders_id",

			}
		},
		methods: {
																																																																											/**
				 * 提交前事件
				 * @param {Object} param 提交参数
				 */
				submit_before: function(param) {
					// console.log('提交前事件', param);
					// 保存计算结果
																																																																																																										this.set_total_purchase_price()
																																																	param = this.form
					// 循环参数
					for(var key in param){
						// 错误回调
						try{
							var value = param[key];
							// 值判断与值校验
							console.log("键 ,值 ,类型" ,key ,value ,value instanceof Date);
							if(value && value instanceof Date){
								param[key] = this.$toTime(value ,"yyyy-MM-dd hh:mm:ss");
							}
						}
						catch(err){
							console.log(key ,"转日期错误：" ,err ,"收到请无视!");
						}
					}
					return param;
				},
						formatDateValue(value) {
		  const date = new Date(value);
		  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
		},
		async submit(param, func){
			if (!param) {
				param = this.form;
			}
						var pm = this.events("submit_before", Object.assign({}, param)) || param;
			var msg = await this.events("submit_check", pm);
			var ret;
			if (msg) {
				this.$toast(msg, 'danger');
			} else {
																																									ret = this.events("submit_main", pm, func);
			}
			return ret;
		},
		
      /**
       * 提交前验证事件
       * @param {Object} 请求参数
       * @return {String} 验证成功返回null, 失败返回错误提示
       */
            submit_check(param) {
      																																																												        return null;
      },
					/**
			 * 获取商家用户用户列表
			 */
			async get_list_user_merchant_users() {
				var json = await this.$get("~/api/user/get_list?user_group=商家用户");
				if(json.result && json.result.list){
					this.list_user_merchant_users = json.result.list;
				}
				else if(json.error){
					console.error(json.error);
				}
			},
		
				
				
				
				
						/**
			 * 获取普通用户用户列表
			 */
			async get_list_user_ordinary_users() {
				var json = await this.$get("~/api/user/get_list?user_group=普通用户");
				if(json.result && json.result.list){
					this.list_user_ordinary_users = json.result.list;
				}
				else if(json.error){
					console.error(json.error);
				}
			},
					async get_user_session_ordinary_users(){
				var _this = this;
				var json = await this.$get("~/api/user_group/get_obj?name=普通用户");
				if(json.result && json.result.obj){
					var source_table = json.result.obj.source_table;
					var user_id = _this.$store.state.user.user_id;
					if (user_id){
						var url = "~/api/"+source_table+"/get_obj?"
						this.$get(url, {"user_id":_this.$store.state.user.user_id}, function(res) {
							if (res.result && res.result.obj) {
								var arr = []
								for (let key in res.result.obj) {
									arr.push(key)
								}
								var arrForm = []
								for (let key in _this.form) {
									arrForm.push(key)
								}
								_this.form["ordinary_users"] = user_id
								_this.disabledObj['ordinary_users' + '_isDisabled'] = true
								for (var i=0;i<arr.length;i++){
                  if (arr[i]!=='examine_state' && arr[i]!=='examine_reply') {
                    for (var j = 0; j < arrForm.length; j++) {
                      if (arr[i] === arrForm[j]) {
                        if (arr[i] !== "ordinary_users") {
                          _this.form[arrForm[j]] = res.result.obj[arr[i]]
                          _this.disabledObj[arrForm[j] + '_isDisabled'] = true
                          break;
                        }
                      }
                    }
                  }
								}
							}
						});
					}
				}
				else if(json.error){
					console.error(json.error);
				}
			},
	
				
				
				
									set_total_purchase_price(){
				this.form.total_purchase_price = parseFloat(this.form.food_prices) * parseFloat(this.form.purchase_quantity)
        let r = /^\+?[1-9][0-9]*$/; // 正整数
        if(!r.test(this.form.total_purchase_price) ){
          this.form.total_purchase_price = this.form.total_purchase_price.toFixed(2);
        }
			},
							// 自动计算精度处理
		toFixed: function(num){
			if (!isNaN(num)) {
				return ((num + '').indexOf('.') == -1) ? num : num.toFixed(2);
			}
		},
				
				
				
		  		get_user_info(name,id){
				var obj = null;
  				  if (name == 'merchant_users'){
					  obj = this.list_user_merchant_users.getObj({"user_id":id});
				  }
            				  if (name == 'ordinary_users'){
					  obj = this.list_user_ordinary_users.getObj({"user_id":id});
				  }
              				var ret = "";
				if(obj){
				  ret = obj.nickname+"-"+obj.username;
				}
				return ret;
			},
			/**
			 * 修改文件
			 * @param { Object } files 上传文件对象
			 * @param { String } str 表单的属性名
			 */
			change_file(files, str) {
				var form = new FormData();
				form.append("file", files[0]);
				this.$post("~/api/catering_orders/upload?", form, (res) => {
					if (res.result) {
						this.form[str] = res.result.url;
					} else if (res.error) {
						this.$toast(res.error.message);
					}
				});
			},
			
			/**
			 * 修改文件
			 * @param { Object } files 上传文件对象
			 * @param { String } str 表单的属性名
			 */
			change_file_multiple(files, str) {
				let _this = this;
				var form = new FormData();
				for (var i = 0; i < files.length; i++) {
					form.set("file", files[i]);
					_this.$post("~/api/catering_orders/upload?", form, (res) => {
						if (res.result) {
							if (_this.form[str].length > 0) {
								_this.form[str].push(res.result.url);
							} else {
								_this.form[str] = [res.result.url];
							}
						} else if (res.error) {
							_this.$toast(res.error.message);
						}
					});
				}
			},

			/**
			 * 获取对象后获取缓存表单
			 * @param {Object} json
			 * @param {Object} func
			 */
			get_obj_before(param){
				var form = $.db.get("form");
				// if (form) {
        //   delete(form.examine_state)
        //   delete(form.examine_reply)
        //   this.obj = $.push(this.obj ,form);
				// 	this.form = $.push(this.form ,form);
				// }
				// var arr = []
				// for (let key in form) {
				// 	arr.push(key)
				// }
				// for (var i=0;i<arr.length;i++){
				// 	this.disabledObj[arr[i] + '_isDisabled'] = true
				// }
        if (form) {
          var arr = []
          for (let key in form) {
            arr.push(key)
          }
          var arrForm = []
          for (let key in this.form) {
            arrForm.push(key)
          }
          for (var i=0;i<arr.length;i++){
            if (arr[i]!=='examine_state' && arr[i]!=='examine_reply') {
              for (var j = 0; j < arrForm.length; j++) {
                if (arrForm[j] === arr[i]) {
                  this.form[arrForm[j]] = form[arr[i]]
                  this.obj[arrForm[j]] = form[arr[i]]
                  this.disabledObj[arrForm[j] + '_isDisabled'] = true
                  break;
                }
              }
			  if(arr[i] === "source_table"){
			  	this.form['source_table'] = form[arr[i]]
			  }
			  if(arr[i] === "source_id"){
			  	this.form['source_id'] = form[arr[i]]
			  }
			  if(arr[i] === "source_user_id"){
			  	this.form['source_user_id'] = form[arr[i]]
			  }
            }
          }
        }
																																				
        $.db.del("form");
				return param;
			},

			/**
			 * 获取对象后获取缓存表单
			 * @param {Object} json
			 * @param {Object} func
			 */
			get_obj_after(json ,func){
				// var form = $.db.get("form");
				// var obj = Object.assign({} ,form ,this.obj);
				// if (obj) {
        //   delete(obj.examine_state)
        //   delete(obj.examine_reply)
				// 	this.obj = $.push(this.obj ,obj);
				// }
				// if (form) {
        //   delete(form.examine_state)
        //   delete(form.examine_reply)
				// 	this.form = $.push(this.form ,form);
				// }

				if(func){
					func(json);
				}
			},

		},
		created() {
						this.get_list_user_merchant_users();
																		this.get_user_session_ordinary_users();
					this.get_list_user_ordinary_users();
																					},
	}
</script>

<style>
	.diy_compute{
		line-height: 40px;
	}
	.diy_field.diy_img_multiple{
		margin: 0;
	}
	.diy_field.diy_img_multiple div{
		float: left;
		position: relative;
		margin: 0 10px 10px 0;
	}
	.diy_field.diy_img_multiple img{
		height: 100px;
		width: auto;
	}
	.diy_field.diy_img_multiple span{
		position: absolute;
		top: 5px;
		right: 5px;
		width: 20px;
		height: 20px;
		background: #0000008a;
		color: #fff;
		line-height: 20px;
		text-align: center;
		border-radius: 100%;
		cursor: pointer;
	}



</style>
